import { ipcRenderer } from 'electron'
import { IpcTerminalKeys } from '../common/enums/ipc.terminal.enum'
export interface ITerminalApi {
  terminalStart: Function
  terminalSend: (command: string) => Promise<void>
  terminalKill: () => Promise<void>
  terminalOutput: (callback: (output: string) => void) => void
  terminalExit: (callback: (code: number) => void) => void
  terminalError: (callback: (error: string) => void) => void
  terminalClear: (callback?: () => void) => void
}
export const terminalApi: ITerminalApi = {
  // terminalApi
  terminalStart: () => ipcRenderer.invoke(IpcTerminalKeys.TERMINAL_START),
  terminalSend: (command: string) => ipcRenderer.invoke(IpcTerminalKeys.TERMINAL_SEND, command),
  terminalKill: () => ipcRenderer.invoke(IpcTerminalKeys.TERMINAL_KILL),
  terminalOutput: (callback: (output: string) => void) => {
    ipcRenderer.on(IpcTerminalKeys.TERMINAL_OUTPUT, (_, output) => callback(output))
  },
  terminalExit: (callback: (code: number) => void) => {
    ipcRenderer.on(IpcTerminalKeys.TERMINAL_EXIT, (_, code) => callback(code))
  },
  terminalError: (callback: (error: string) => void) => {
    ipcRenderer.on(IpcTerminalKeys.TERMINAL_ERROR, (_, error) => callback(error))
  },
  terminalClear: (callback?: () => void) => {
    ipcRenderer.on(IpcTerminalKeys.TERMINAL_CLEAR, () => callback && callback())
  }
}
